package com.spic.business.home.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spic.business.home.domain.WorkProgressView;
import com.spic.business.home.mapper.HomeMapper;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.security.service.TokenService;
import com.spic.system.api.domain.SysUser;
import com.spic.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 290512
 * @create 2022-01-12 19:52
 */
@Service
public class HomeService
{
    @Autowired
    private HomeMapper homeMapper;
    @Autowired
    private TokenService tokenService;
    public  String[] TYPE_NAME ={"违章举报","重大事项","考试记录","超速记录","隐患排查","二级动火票"};
    public List<WorkProgressView> getHomeList(){
        // 获取当前的用户
        LoginUser loginUser = tokenService.getLoginUser();
        if (com.spic.common.core.utils.StringUtils.isNotNull(loginUser))
        {
            SysUser currentUser = loginUser.getSysUser();
            QueryWrapper<WorkProgressView> sectionQueryWrapper = new QueryWrapper<>();
            // 如果是超级管理员，则不过滤数据
            if (com.spic.common.core.utils.StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
            {
                sectionQueryWrapper.eq("user_id", SecurityUtils.getUserId());
                List<WorkProgressView> newList = new ArrayList<>();
                List<WorkProgressView> workProgressViews = homeMapper.selectList(sectionQueryWrapper);
                insertValue(workProgressViews);
                return workProgressViews;
            }else{
                List<WorkProgressView> workProgressViews = homeMapper.selectList(null);
                List<WorkProgressView> newList = new ArrayList<>();
                workProgressViews.parallelStream().collect(Collectors.groupingBy(WorkProgressView::getName, Collectors.toList()))
                        .forEach((id, stu) -> {
                            stu.stream().reduce((a, b) -> new WorkProgressView (a.getNum()+b.getNum(),a.getUserId(),a.getName())).ifPresent(newList ::add);
                        });


                insertValue(newList);
                return newList;

            }
        }

        return null;
    }

    private  void insertValue(List<WorkProgressView> newList){
        for(int i = 0;i<TYPE_NAME.length;i++){
            int finalI = i;
            boolean present = newList.stream().filter(item -> item.getName().equals(TYPE_NAME[finalI])).findAny().isPresent();
            if(present){
                continue;
            }else{
                WorkProgressView workProgressView = new WorkProgressView(0,SecurityUtils.getUserId(),TYPE_NAME[finalI]);
                newList.add(workProgressView);
            }
        }
    }
}
